The C++ language has four typecast operators:
Typecasting is making a variable of one type, such as an int, act like another type, a char, for one single operation. To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable. (char)a will make 'a' function as a char.
C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion, known in C++ as type-casting.
double x = 10.3;
int y;
y = x; //implicit conversion
y = int (x); //functional notation – explicit typecast
y = (int) x; //c -like cast notation – explicit typecast
y = static_cast<int>(x); //c++ -like cast notation - explicit typecast
Note: It is recommended to use explicit conversions (static_cast) when programming.
We have:
The static_cast can be used for all these types of conversion. Take a look at an example:
int a = 5;
int b = 2;
double out;
//typecast a to double
out = static_cast<double>(a)/b
It may take some time to get used to the notation of the typecast statement. (The rumour goes that Bjarne Stroustrup made it difficult on purpose, to discourage the use of typecasting.) Between the angle brackets you place to which type the object should be casted. Between the parentheses you place the object that is casted.
It is not possible to use static_cast on const objects to non-const objects. For this you have to use const_cast.
If an automatic conversion is valid (from enum to int for instance) then you can use static_cast to do the opposite (from int to enum).
my_numbers {
a=10,
c=100,
e=1000
};
const my_numbers b = static_cast<my_numbers> (50);
const my_numbers d = static_cast<my_numbers> (500);
Note: We add some new values (b and d). These are type-cast from int to enum.